<%--
   * 【描 述】：审核流程
   * 【环 境】：JAVA 1.7.0_13
   *  @author         柴志鹏  CHAIZP@GMAIL.COM
   *  @version        v1.0 2014-11-12
   *  @since          2014-11-12
 --%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ include file="/include/head.jsp"%>
<html>
  <head>
    <title>审核流程管理</title>
    <style type="text/css">
    	.Wrench{background-image:url(../../images/icons/wrench.png)!important;}
    </style>
    <script type="text/javascript">
    	Ext.onReady(function(){
    		Ext.QuickTips.init();
    		Ext.form.Field.prototype.msgTarget = 'qtip';
    		//字典数据源
    		var dictStore = cf_queryDictByCode('999');
    		//查询审核类型数据源
    		var typeStore = new Ext.data.Store({
    			proxy: new Ext.data.HttpProxy({
    				url: 'AuditAction!queryAuditType.do'
    			}),
    			reader: new Ext.data.JsonReader({
    				totalProperty: 'total',
    				root: 'list'
    			}, new Ext.data.Record.create([
    				{name: 'id'},
    				{name: 'auditName'},
    				{name: 'auditType'},
    				{name: 'remark'},
    				{name: 'enableStatus'}
    			])),
    			remoteSort: false,//是否远程排序
    			autoLoad: {
    				params: {
    					start: PAGING_START_INDEX,
    					limit: PAGING_PAGE_SIZE
    				}
    			}
    		});
    		
    		//根据审核类型id查询审核流程数据源
    		var processStore = new Ext.data.Store({
    			proxy: new Ext.data.HttpProxy({
    				url: 'AuditAction!queryAuditProcessByTypeId.do'
    			}),
    			reader: new Ext.data.JsonReader({
    				totalProperty: 'total',
    				root: 'list'
    			}, new Ext.data.Record.create([
    				{name: 'id'},
    				{name: 'jobName'},
    				{name: 'department'},
    				{name: 'auditProcess'}
    			])),
    			remoteSort: false,
    			autoLoad: false
    		});
    		
    		//选择框
    		var typeModel = new Ext.grid.CheckboxSelectionModel({
    			singleSelect: true, //单选
    			header: '',//空代替checkbox全选框
    			listeners: {
    				//行选中事件
    				'rowselect': function(selMode, rowIndex, record) {
    					//将类型Id赋给流程typeId字段
    					processStore.baseParams = {
    						'typeId': record.get('id')
    					};
    					
    					//重新加载审核顺序数据源
    					processStore.reload({
    						params: {
    							'start': PAGING_START_INDEX,
    							'limit': PAGING_PAGE_SIZE
    						}
    					});
    				}
    			}
    		});
    		
    		//审核类型列表
    		var typeColumn = new Ext.grid.ColumnModel({
    			defaults: {
    				sortable: true,//默认全部列可排序
    				align: 'center'
    			},
    			columns: [
    				typeModel,
    				new Ext.grid.RowNumberer({
    					id: 'rownum',
    					header: '序号',
    					width: 40
    				}), {
    					id: 'id',
    					header: '主键Id',
    					dataIndex: 'id',
    					width: 10,
    					hidden: true
    				}, {
    					id: 'auditName',
    					header: '审核名称',
    					dataIndex: 'auditName',
    					width: 25
    				}, {
    					id: 'auditType',
    					header: '审核类型',
    					dataIndex: 'auditType',
    					width: 20
    				}, {
    					id: 'remark',
    					header: '备注',
    					dataIndex: 'remark',
    					width: 25,
    					renderer: function(value, metaData, record, rowIndex, colIndex, store) {
    						metaData.attr = 'ext:qtip="'+ value +'"';
			        		return value;
    					}
    				}, {
    					id: 'enableStatus',
    					header: '启用状态',
    					dataIndex: 'enableStatus',
    					width: 20,
    					renderer: function(value, metaData, record, rowIndex, colIndex, store) {
    						//返回带有颜色的状态
    						return cf_enableStatus(value);
    					}
    				}
    			]
    		});
    		
    		//定义流程选项框
    		var proModel = new Ext.grid.CheckboxSelectionModel();
    		var proColumn = new Ext.grid.ColumnModel({
    			defaults: {
    				sortable: true,//默认全部列可排序
    				align: 'center'
    			},
    			columns: [
    				proModel,
    				new Ext.grid.RowNumberer({
    					id: 'rownum',
    					header: '顺序',
    					width: 50
    				}), {
    					id: 'id',
    					header: '主键Id',
    					dataIndex: 'id',
    					width: 25,
    					hidden: true
    				}, {
    					id: 'jobName',
    					header: '岗位名称',
    					dataIndex: 'jobName',
    					width: 25
    				}, {
    					id: 'department',
    					header: '部门',
    					dataIndex: 'department',
    					width: 25,
    					renderer: function(value, cellmeta, record) {
							var rec = dictStore.find('dictValue',value);
							if(rec == undefined||rec ==null||dictStore.getAt(rec).data==null){
								return value;
							}else{
								return dictStore.getAt(rec).get('dictLabel');
							}
	    				}
    				}, {
    					id: 'auditProcess',
    					header: '审核顺序',
    					dataIndex: 'auditProcess',
    					width: 20,
    					hidden: true
    				}
    			]
    		});
//=========================================
			var viewport = new Ext.Viewport({
				layout: 'border',
				items: [
					new Ext.grid.GridPanel({
						region: 'west',//西
						id: 'typeGrid',
						autoScroll: true,
						store: typeStore,
						cm: typeColumn,
						sm: typeModel,
						frame: false,
						trackMouseOver: true,//鼠标经过痕迹
						loadMask: true,
						loadMask: {msg: 'loading...'},
						tbar: [{
								text: '新增',
								iconCls: 'addBtn',
								handler: function() {
									typeController('C', this.text);
								}
							}, {
								text: '修改',
								iconCls: 'editBtn',
								handler: function() {
									var grid = Ext.getCmp('typeGrid');
									var record = grid.getSelectionModel().getSelected();
									if(record) {
										typeController('U', this.text, record);
									} else {
										Ext.MessageBox.alert('提示', '请选择一条记录');
									}
								}
							}, {
								text: '删除',
								iconCls: 'deleteBtn',
								handler: function() {
									var grid = Ext.getCmp('typeGrid');
									var record = grid.getSelectionModel().getSelected();
									if(record) {
										Ext.MessageBox.confirm('提示','确认删除?', 
											function(btn) {
												if(btn == BUTTON_YES) {
													Ext.Ajax.request({
														url: 'AuditAction!auditTypeController.do',
														method: 'POST',
														params: {
															'at.cudType': 'D',
															'at.id': record.get('id')
														},
														success: function(result, request) {
															typeStore.remove(record);
															refresh('type');
														},
														failure: function() {
															Ext.MessageBox.alert('提示', '操作失败!请重试.');
														}
													});
												}
											}
										);
									}
								}
							}, '->', '审核类型',
							new Ext.form.TwinTriggerField({
							    trigger1Class: 'x-form-clear-trigger',
							    trigger2Class: 'x-form-search-trigger',
							    hideTrigger1: true,
							    autoWidth: true,
							    listeners: {
							        'specialkey': function(f, e){
							        	if(e.getKey() == e.ENTER){
							            	this.onTrigger2Click();
							        	}
							    	}
							 	},
							 	onTrigger1Click:function(){
							    	this.setRawValue('');
							     	this.triggers[0].hide();
							    	return false;
							 	},
							 	onTrigger2Click:function() {
							    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
						        	this.triggers[0].show();
							        typeStore.reload({
							        	params: {
							        		'start': PAGING_START_INDEX,
											'limit': PAGING_PAGE_SIZE,
							        		'auditType': name
							        	}
							    	});
								}
							})
						],
						bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, typeStore),
						viewConfig: {
							forceFit: true,//根据column进行百分比设置
							scrollOffset: 0//grid右侧滚动条预留大小
						},
						listeners: {
							'afterrender': function(grid) {
								setTimeout(function() {//渲染速度问题延迟500毫秒
									if(typeStore.getCount() > 0) {
										//默认选中首行
										grid.getSelectionModel().selectRow(0);
									}
								}, 1000);
							}
						}
					}),
					new Ext.grid.GridPanel({
						region: 'center',// 中
						id: 'processGrid',
						autoScroll: true,
						store: processStore,
						cm: proColumn,
						sm: proModel,
						frame: false,
						trackMouseOver: true,// 鼠标划过痕迹
						loadMask: true,
						loadMask: {msg: 'loading...'},
						enableDragDrop: true,// 启用拖放
						ddGroup: 'auditGridDDGroup',
						tbar: [
							{
								text: '操作',
								iconCls: 'Wrench',
								handler: function() {
									var grid = Ext.getCmp('typeGrid');
									var record = grid.getSelectionModel().getSelected();
									if(record) {
										processController(this.text, record.get('id'));
									} else {
										Ext.MessageBox.alert('提示', '请选择一条记录');
									}
								}
							}
						],
						bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, processStore),
						viewConfig: {
							forceFit: true,//根据column进行百分比设置
							scrollOffset: 0//grid右侧滚动条预留大小
						},
						listeners: {
							'afterrender': function(grid) {
								// 拖拽事件
								new Ext.dd.DropTarget(grid.container, {
									ddGroup: 'auditGridDDGroup',
									copy: false,// 决定拖放以后是执行剪切操作还是复制操作 
									notifyDrop: function(dd, e, data){
										//选中了多少行
										var rows = data.selections;
										//拖动到第几行
										var index = dd.getDragData(e).rowIndex;
										if(typeof(index) == "undefined") {
											return;
										}
										//修改store
										for(i = 0; i < rows.length; i++) {
											var rowData = rows[i];
											if (!this.copy) processStore.remove(rowData);
											processStore.insert(index, rowData);
										}
										// 将排序后的数据源格式化为数组
										var count = processStore.getCount();
										var data = "[";
										for(var i = 0; i < count; i++) {
											data += "{id:"+ processStore.getAt(i).id +"}"
											if (i < count - 1)	data = data + ",";
										}
										data += "]";
										Ext.Ajax.request({
											url: 'AuditAction!sortProcess.do',
											method: 'POST',
											params: {
												'data': data
											},
											success: function(result, request) {
												refresh('process');
											},
											failure: function(result, request) {
												Ext.MessageBox.alert('提示', '操作失败!请重试.');
											}
										});
									}
								});
							}
						}
					})
				],
				listeners: {
					'resize': function(view, adjWidth, adjHeight, rawWidth, rawHeight) {
						var grid = Ext.getCmp('typeGrid');
						if(Ext.isIE) {
							grid.setWidth((adjWidth=='auto'?700:adjWidth)*0.6);
						} else {
							grid.setWidth('60%');
						}
					}
				}
			});

			function typeController(cudType, title, record) {
				var typeForm = new Ext.form.FormPanel({
		            id: 'typeForm',
		            region: 'center',
		            autoScroll: true,
		            layout: 'form',
		            labelWidth: 70,
		            autoWidth: true,
		            labelAlign: 'right',
		            bodyStyle: 'padding:5px 5px 0',
		            border: true,
		            frame: true,
		            fileUpload: true,
		            buttonAlign: 'center',
		            defaults: {
			            anchor: '90%'
				    },
		            items:[
		            	new Ext.form.Hidden({
		            		itemId: 'id',
		            		name: 'at.id'
		            	}),
		            	new Ext.form.TextField({
		            		itemId: 'auditName',
		            		name: 'at.auditName',
		            		fieldLabel: cf_getRequiredItem('审核名称'),
		            		maxLength: 20,
		            		maxLengthText: '名称长度不可大于{0}字符',
		            		allowBlank: false
		            	}),
		            	new Ext.form.TextField({
		            		itemId: 'auditType',
		            		name: 'at.auditType',
		            		fieldLabel: cf_getRequiredItem('审核类型'),
		            		maxLength: 20,
		            		maxLengthText: '类型长度不可大于{0}字符',
		            		allowBlank: false
		            	}),
		            	new Ext.form.RadioGroup({
		            		itemId: 'enableStatus',
		            		fieldLabel: '启用状态',
		            		columns: [50, 50],
		            		items: [
		            			{boxLabel: '启用', inputValue: 1, name: 'at.enableStatus', checked: true},
		            			{boxLabel: '禁用', inputValue: 0, name: 'at.enableStatus'}
		            		]
		            	}),
		            	new Ext.form.TextArea({
		            		itemId: 'remark',
		            		name: 'at.remark',
		            		fieldLabel: '备注'
		            	})
		            ],
		            buttons: [
		            	{
		            		text: '保存',
		            		handler: function() {
		            			if(!typeForm.form.isValid()) {
		            				return false;
		            			} else {
		            				typeForm.getForm().submit({
		            					url: 'AuditAction!auditTypeController.do',
		            					method: 'POST',
		            					submitEmptyText: false,
		            					params: {
		            						'at.cudType': cudType
		            					},
		            					success: function(result, request) {
		            						win.hide('audit', function() {
		            							win.close();
		            							refresh('type');
		            						}, true);
		            					},
		            					failure: function(result, request) {
		            						Ext.MessageBox.alert('提示', '保存失败!');
		            					}
		            				});
		            			}
		            		}
		            	}, {
		            		text: '取消',
		            		handler: function() {
		            			win.hide('audit', function(){
		            				win.close();
		            			}, true);
		            		}
		            	}
		            ]
		        });
				
				win = new Ext.Window({
		            title: title,
		            layout: 'border',
		            width: 350,
		            height: 235,
		            modal: true,
		            resizable: true,
		            items: typeForm,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					listeners: {
		        		show: function(win) {
		        			if (record) {
								typeForm.getForm().loadRecord(record);
							}
		        		}
		            }
		        });
		        win.show('audit');// 淡出窗口
			}
			
			function processController(title, typeId) {
				var optGrid = new Ext.grid.GridPanel({
					id: 'optGrid',
					title: '<div style="text-align:center;">可选岗位</div>',
					autoScroll: true,
					border: false,
					store: new Ext.data.JsonStore({  
					    url: 'AuditAction!getOptionallyProcess.do',
					    fields: [
						    {name: 'id'},
							{name: 'jobName'},
							{name: 'jobId'},
						    {name: 'department'}
					    ],
					    autoLoad: {
					    	params: {
					    		'typeId': typeId
					    	}
					    }
					}),
					cm: new Ext.grid.ColumnModel({
						defaults: {
							sortable: false,//禁止排序
							align: 'center'
						},
						columns: [
							{id: 'id', 			header: '主键Id', 	dataIndex: 'id', 		width: 10, hidden: true},
							{id: 'jobName', 	header: '岗位名称', 	dataIndex: 'jobName', 	width: 40},
							{id: 'department', 	header: '所在部门', 	dataIndex: 'department',width: 40, 
								renderer: function(value, cellmeta, record) {
									var rec = dictStore.find('dictValue',value);
									if(rec == undefined||rec ==null||dictStore.getAt(rec).data==null){
										return value;
									} else {
										return dictStore.getAt(rec).get('dictLabel');
									}
			    				}
							}
						]
					}),
					stripeRows: true,
					//trackMouseOver: true,// 鼠标划过痕迹
					loadMask: true,
					loadMarks: {msg: 'loading..'},
					viewConfig: {
						forceFit: true//根据column进行百分比设置
					},
					listeners: {
						//行双击事件
						'rowdblclick': function(grid, rowIndex, event) {
							//获取选中行
							var record = grid.getSelectionModel().getSelected();
                        	grid.store.remove(record);
                        	selGrid.store.insert(selGrid.store.getCount(), record);
						}
					}
				});
				
				var selGrid = new Ext.grid.GridPanel({
					id: 'selGrid',
					title: '<div style="text-align:center;">已选岗位</div>',
					autoScroll: true,
					border: false,
					store: new Ext.data.JsonStore({  
					    url: 'AuditAction!getSelectedProcess.do',
					    fields: [
						    {name: 'id'},
							{name: 'jobName'},
							{name: 'jobId'},
						    {name: 'department'} 
					    ],
					    autoLoad: {
					    	params: {
					    		'typeId': typeId
					    	}
					    }
					}),
					cm: new Ext.grid.ColumnModel({
						defaults: {
							sortable: false,//禁止排序
							align: 'center'
						},
						columns: [
							{id: 'id', 			header: '主键Id', 	dataIndex: 'id', 		width: 10, hidden: true},
							{id: 'jobName', 	header: '岗位名称', 	dataIndex: 'jobName', 	width: 40},
							{id: 'department', 	header: '所在部门', 	dataIndex: 'department',width: 40, 
								renderer: function(value, cellmeta, record) {
									var rec = dictStore.find('dictValue',value);
									if(rec == undefined||rec ==null||dictStore.getAt(rec).data==null){
										return value;
									} else {
										return dictStore.getAt(rec).get('dictLabel');
									}
			    				}
							}
						]
					}),
					enableDragDrop: true,
					ddGroup: 'optGridDDGroup',
					stripeRows: true,
					//trackMouseOver: true,// 鼠标划过痕迹
					loadMask: true,
					loadMarks: {msg: 'loading..'},
					viewConfig: {
						forceFit: true//根据column进行百分比设置
					},
					listeners: {
						'rowdblclick': function(grid, rowIndex, event) {
							var record = grid.getSelectionModel().getSelected();
							grid.store.remove(record);
							optGrid.store.insert(optGrid.store.getCount(), record);
						}
					}
				});
				
				
				var win = new Ext.Window({
					title: title,
					layout: 'column',
					width: 500,
					height: 300,
					modal: true,
					closeAction: 'close',
					resizable: false,
					constrainHeader: true,
					buttonAlign: 'center',
					items: [{
						columnWidth: .47,
						items: [optGrid]
					}, {
						columnWidth: .06,
						items: [
							new Ext.Panel({
								id: 'prcBtns',
								border: false,
								defaults: { xtype: 'button' },
								layout: {
									type: 'vbox',
									pack: 'center',//纵向对齐方式 start：从顶部；center：从中部；end：从底部
									align: 'center'//对齐方式 center、left、right：居中、左对齐、右对齐；stretch：延伸；stretchmax：以最大的元素为标准延伸
								},
								items: [
									{
										text: '&gt;&gt;',//>>
										handler: function() {
											//获取选中的"可选"行
											var records = optGrid.getSelectionModel().getSelections();
											if(records.length != 0) {
												//循环选中并移除store，将其插入到"已选"数据源中
												Ext.each(records, function(r) {
						                        	optGrid.store.remove(r);
						                        	selGrid.store.insert(selGrid.store.getCount(), r);
						                        });
											}
										}
									}, {
										//换行
										xtype: 'panel',
										border: false,
										html: '<br/><br/>'
									},{
										text: '&lt;&lt;',//<<
										handler: function() {
											//获取选中的"已选"行
											var records = selGrid.getSelectionModel().getSelections();
											if(records.length != 0) {
												//循环选中并移除store，将其插入到"可选"数据源中
												Ext.each(records, function(r) {
													selGrid.store.remove(r);
													optGrid.store.insert(optGrid.store.getCount(), r);
												});
											}
										}
									}
								]
							})
						]
					}, {
						columnWidth: .47,
						items: [selGrid]
					}],
					listeners: {
						'afterrender': function(win) {
							optGrid.setHeight(win.height-66);
							selGrid.setHeight(win.height-66);
							Ext.getCmp('prcBtns').setHeight(win.height-66);
							//"已选"拖拽事件
							var optGridDropTarget = new Ext.dd.DropTarget(selGrid.container, {
								ddGroup: 'optGridDDGroup',
								copy: false,// 决定拖放以后是执行剪切操作还是复制操作 
								notifyDrop: function(ddSource, e, data) {
									// 获取全部选中数据
									var records = ddSource.dragData.selections;
									//拖动到第几行
									var index = ddSource.getDragData(e).rowIndex;
									//如果要拖拽到的grid处没有位置则插入到最后
									if(typeof(index) == "undefined") {
										//index = selGrid.store.getCount();
										return;
									}
			                        Ext.each(records, function(record) {
			                        	selGrid.store.remove(record);
			                        	selGrid.store.insert(index, record);
			                        });
			                        return true
								}
							});
						}
					},
					buttons: [
						{
							text: '保存',
							handler: function() {
								var count = selGrid.store.getCount();
								var data = "[";
								for(var i = 0; i < count; i++) {
									data += "{id:"+ selGrid.store.getAt(i).id +","
									data += "jobId:"+ selGrid.store.getAt(i).get('jobId') +"}"
									if (i < count - 1)	data = data + ",";
								}
								data += "]";
								Ext.Ajax.request({
									url: 'AuditAction!auditProcessController.do',
									method: 'POST',
									params: {
										'typeId': typeId,
										'data': data
									},
									success: function(result, request) {
										win.hide('audit', function() {
	            							win.close();
	            							refresh('process');
	            						}, true);
									},
									failure: function(result, request) {
										Ext.MessageBox.alert('提示', '操作失败!请重试.');
									}
								});
							}
						}, {
							text: '取消',
							handler: function() {
								win.hide('audit', function() {
           							win.close();
           						}, true);
							}
						}
					]
				});
				win.show('audit');
			}
			
    		
    		function refresh(type) {
				if(type == 'type') {
					typeStore.modified = [];
		           	typeStore.removeAll();
		  			typeStore.reload();
				} else if(type == 'process') {
					processStore.modified = [];
		           	processStore.removeAll();
		  			processStore.reload();
				}
	    	}
		});
    </script>
  </head>
  
  <body>
    <div id="audit"></div>
  </body>
</html>